#!/usr/bin/env python 
# -*- coding:utf-8 -*-
"""
@Time:2022/3/14 下午8:34"
@Author:lydia_liu"
@File:goods_api.py
@function:
"""
from jsonpath import jsonpath

from litemallApiPrac.api_objects.litemall import Litemail
from litemallApiPrac.utils import logger


class GoodsApi(Litemail):

    # 商品上架
    def create(self,goods_Sn:str,goods_name:str):
        logger.info(f"商品编号:{goods_Sn},商品名称：{goods_name}")

        data = {
            "url":f"{self.base_url}/admin/goods/create",
            "method":"POST",
            "headers":{"X-Litemall-Admin-Token":self.token},
            "json":{
                "goods":{
                    "goodsSn":goods_Sn,
                    "name":goods_name},
                "specifications":[
                    {"specification":"规格",
                        "value":"标准",
                        "picUrl":""}],
                "products":[
                    {
                        "id":0,
                        "specifications":[
                            "标准"
                        ],
                        "price":0,
                        "number":0,
                        "url":""
                    }
                ],
                "attributes":[
                    {"attribute":"材质", "value":"纯棉"}
                ]
            }
        }
        r = self.do_request(data)
        logger.info(r.json())
        return r


    # 商品查询
    def query(self, goods_name: str = None, goodsSn: str = None, goodsId: str = None):
        # url = "http://litemall.hogwarts.ceshiren.com/admin/goods/list"


        data = {
            "url":f"{self.base_url}/admin/goods/list",
            "method":"get",
            "headers":{"X-Litemall-Admin-Token":self.token},
            "params":{
                "goodsSn":goodsSn,
                "name":goods_name,
                "goodsId":goodsId}
        }
        r = self.do_request(data)
        return r

    # 商品删除
    def delete(self,goods_id:int,):
        # url = "http://litemall.hogwarts.ceshiren.com/admin/goods/delete"
        data = {
            "url":f"{self.base_url}/admin/goods/delete",
            "method":"post",
            "headers": {"X-Litemall-Admin-Token": self.token},
            "json":{
                "id":goods_id
            }
        }
        r = self.do_request(data)
        return r

    def do_find_id(self,goods_name:str):
        r1 = self.query(goods_name=goods_name)
        result = jsonpath(r1.json(), "$..id")
        print(result)
        if result and len(result) == 1:
            my_id = result[0]
        else:
            return None

        return my_id
